/**
 * mrcode ui 组件
 * 依赖文件：
 *      1. jquery.js
 *      2. 部分组件依赖于bootstrap，在具体的ui组件描述里面有说明
 *      3. arttemplate插件
 *      4. 自家的poplayer组件
 *
 * @type {{}}
 */
;(function (window) {
    'use strict';
    var MrcodeUi = {
        /** 整个ui配置参数 */
        Config: {
            Alert: {
                /** 弹窗默认配置 */
                PopLayer: {
                    animateEntrance: 'flipInX',
                    animateClosing: 'flipOutX',
                    onConfirm_title: "确定",
                    onConfirm_style: "danger",
                    onCancel_title: "取消",
                    onCancel_style: "default",
                    onConfirm_info_title: "我知道了",
                    onConfirm_info_style: "info",
                }
            }
        },
        /** 工具类 */
        Utils: {
            /**
             * 弹窗对象居中
             * @param target
             */
            centerModals: function (target) {
                $(target).each(function (i) {
                    var $clone = $(this).clone().css('display', 'block').appendTo('body');
                    var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
                    top = top > 0 ? top : 0;
                    $clone.remove();
                    $(this).find('.modal-content').css("margin-top", top);
                });
            },
            /**
             * 添加动态效果，
             * @param target 目标窗体jquery对象
             * @param aniName animated 中的效果名称
             * @param fun 效果执行完成后，需要执行的方法
             */
            addAni: function (target, aniName, fun) {
                target.addClass(aniName + ' animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                    $(this).removeClass(aniName + ' animated');
                    if (fun) {
                        fun();
                    }
                });
            },
            /**
             * 延迟加载效果，页面调用一次即可，以下两个css里面都可以加上特效哦
             * @param beforeCssName 隐藏时候的css名称
             * @param afterCssName 显示的时候的css名称
             */
            lzLoad: function (beforeCssName, afterCssName) {
                lz('.' + beforeCssName, afterCssName);
                function lz(before, after) {
                    var fadeElems = $(before),
                        fadeElemsLength = fadeElems.length,
                        i = 0,
                        interval = 50;

                    function incFade() {
                        if (i < fadeElemsLength) {
                            fadeElems[i].className += ' ' + after;
                            i++;
                            setTimeout(incFade, interval);
                        }
                    }

                    setTimeout(incFade, interval);
                }
            },
            /**
             * 创建标签
             * @param naem
             * @returns {jQuery|HTMLElement}
             */
            createTag: function (naem) {
                return $("<" + name + "></" + name + ">");
            }
        },
        Modal_dialog: {
            /**
             * bs v3 模态框居中
             * @param target
             */
            center: function (target) {
                var $target = $(target);
                $(window).on('resize', MrcodeUi.Utils.centerModals($target));
                $target.on('show.bs.modal', MrcodeUi.Utils.centerModals($target));
            }
        },
        /** 弹窗组件 **/
        Alert: {
            /** alert 组件-模版 */
            template: {
                /** 闪现提示框 **/
                sx: '<div id="comm_ui_alert_sx_id" class="alert alert-dismissible text-center" role="alert">' +
                '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                '<span aria-hidden="true">&times;</span>' +
                '</button>' +
                '<span class="comm_ui_alert_sx_body"></span>' +
                '</div>'
            },
            /** 闪现提示 */
            sx: {
                /**
                 * 基于bootstrap的alert闪现提示
                 *
                 * 支持的参数：
                 *  body：需要显示的消息，可以是html代码
                 *  timeout：超时时间，[默认两秒]
                 *  scene ：提示框场景样式[默认success]，以下几个选择，对应bootstrap中的场景
                 *      success
                 *      info
                 *      warning
                 *      danger
                 * @param option
                 */
                sx: function (option) {
                    var body = option.body; //提示内容
                    var timeout = option.timeout; //超时退出
                    var scene = option.scene; //场景
                    if (!timeout) {
                        timeout = 2000;
                    }
                    if (!scene) {
                        scene = "alert-success";
                    } else if ("success" == scene) {
                        scene = "alert-success";
                    } else if ("info" == scene) {
                        scene = "alert-info";
                    } else if ("warning" == scene) {
                        scene = "alert-warning";
                    } else if ("danger" == scene) {
                        scene = "alert-danger";
                    } else {
                        scene = "alert-success";
                    }
                    if (!body) {
                        body = option;
                    }

                    var $alert = $(MrcodeUi.Alert.template.sx);
                    $alert.find(".comm_ui_alert_sx_body").html(body);
                    $alert.css({
                        "position": "fixed",
                        "top": 0,
                        "z-index": 99999,
                        "left": 0,
                        "right": 0
                    });
                    $alert.addClass(scene);
                    $("body").append($alert);
                    MrcodeUi.Utils.addAni($alert, "fadeInDown", function () {
                        setTimeout(function () {
                            MrcodeUi.Utils.addAni($alert, "fadeOut", function () {
                                $alert.remove();
                            });
                        }, timeout);
                    });
                },
                success: function (body) {
                    var option = {"body": body, "scene": "success"};
                    this.sx(option);
                },
                info: function (body) {
                    var option = {"body": body, "scene": "info"};
                    this.sx(option);
                },
                warning: function (body) {
                    var option = {"body": body, "scene": "warning"};
                    this.sx(option);
                },
                danger: function (body) {
                    var option = {"body": body, "scene": "danger"};
                    this.sx(option);
                }
            },
            /** 弹窗提示:
             * =================
             * 1. 自家的poplayer 组件
             * */
            popLayer: {
                /**
                 * 带有确定/取消两个按钮的弹窗，弹窗自定义是否居中，无弹窗标题
                 * @param body 显示内容
                 * @param onCancelTitle 取消按钮标题
                 * @param onConfirmTitle 确定按钮标题
                 * @param onConfirmAction 确定按钮回调函数，可为空，请传递null
                 * @returns {poplayer} 返回该对象
                 */
                popYN: function (body, onCancelTitle, onConfirmTitle, onConfirmAction, isCenter) {
                    var center = "none";
                    if (isCenter) {
                        center = "center";
                    }
                    return new MrcodePopLayer({
                        'position': center,
                        'animateEntrance': MrcodeUi.Config.Alert.PopLayer.animateEntrance,
                        'animateClosing': MrcodeUi.Config.Alert.PopLayer.animateClosing,
                        'content': body,
                        'dialog': "confirm",
                        'onCancel': {text: onCancelTitle},
                        'onConfirm': {
                            text: onConfirmTitle,
                            action: function (me) {
                                if (onConfirmAction) {
                                    return onConfirmAction(me);
                                } else {
                                    return true;
                                }
                            }
                        }
                    });
                },
                /**
                 * 只有确定按钮
                 * @param body
                 * @param onConfirmTitle
                 * @param onConfirmAction
                 * @returns {*|MrcodePopLayer}
                 */
                popYCenter: function (body, onConfirmTitle, onConfirmAction) {
                    return new MrcodePopLayer({
                        'position': "center",
                        'animateEntrance': MrcodeUi.Config.Alert.PopLayer.animateEntrance,
                        'animateClosing': MrcodeUi.Config.Alert.PopLayer.animateClosing,
                        'content': body,
                        'dialog': "confirm",
                        'onConfirm': {
                            text: onConfirmTitle,
                            style: MrcodeUi.Config.Alert.PopLayer.onConfirm_style,
                            action: function (me) {
                                if (onConfirmAction) {
                                    return onConfirmAction(me);
                                } else {
                                    return true;
                                }
                            }
                        }
                    });
                },
                popYCenterTtile: function (body, title, onConfirmTitle, onConfirmAction) {
                    return new MrcodePopLayer({
                        'position': "center",
                        'title': title,
                        'animateEntrance': MrcodeUi.Config.Alert.PopLayer.animateEntrance,
                        'animateClosing': MrcodeUi.Config.Alert.PopLayer.animateClosing,
                        'content': body,
                        'dialog': "confirm",
                        'onConfirm': {
                            text: onConfirmTitle,
                            style: MrcodeUi.Config.Alert.PopLayer.onConfirm_style,
                            action: function (me) {
                                if (onConfirmAction) {
                                    return onConfirmAction(me);
                                } else {
                                    return true;
                                }
                            }
                        }
                    });
                },
                /**
                 * info只有确定按钮：简洁版
                 * @param body
                 * @returns {*|MrcodePopLayer}
                 */
                popYCInfo: function (body) {
                    return new MrcodePopLayer({
                        'position': "center",
                        'animateEntrance': MrcodeUi.Config.Alert.PopLayer.animateEntrance,
                        'animateClosing': MrcodeUi.Config.Alert.PopLayer.animateClosing,
                        'content': body,
                        'dialog': "confirm",
                        'onConfirm': {
                            text: MrcodeUi.Config.Alert.PopLayer.onConfirm_info_title,
                            style: MrcodeUi.Config.Alert.PopLayer.onConfirm_info_style
                        }
                    });
                },

                /**
                 * 网站 统一使用该确定/取消弹窗
                 * @param body
                 * @param onCancelTitle
                 * @param onConfirmTitle
                 * @param onConfirmAction
                 * @returns {*|MrcodePopLayer}
                 */
                popYNCenter: function (body, onCancelTitle, onConfirmTitle, onConfirmAction) {
                    return new MrcodePopLayer({
                        'position': "center",
                        'animateEntrance': 'flipInX',
                        'animateClosing': 'flipOutX',
                        'content': body,
                        'dialog': "confirm",
                        'onCancel': {text: onCancelTitle},
                        'onConfirm': {
                            text: onConfirmTitle,
                            action: function (me) {
                                if (onConfirmAction) {
                                    return onConfirmAction(me);
                                } else {
                                    return true;
                                }
                            }
                        }
                    });
                },
                popYNTitleCenter: function (title, body, onCancelTitle, onConfirmTitle, onConfirmAction) {
                    return new MrcodePopLayer({
                        'position': "center",
                        'animateEntrance': 'flipInX',
                        'animateClosing': 'flipOutX',
                        'title': title,
                        'content': body,
                        'dialog': "confirm",
                        'onCancel': {text: onCancelTitle},
                        'onConfirm': {
                            text: onConfirmTitle,
                            action: function (me) {
                                if (onConfirmAction) {
                                    return onConfirmAction(me);
                                } else {
                                    return true;
                                }
                            }
                        }
                    });
                },
                /**
                 * loading 消息框
                 * @param body 显示信息
                 * @param isAutoClose 是否自动关闭
                 * @returns {*|MrcodePopLayer}
                 */
                popLoading: function (body, isAutoClose) {
                    if (!body) {
                        body = "请稍后..";
                    }
                    if (isAutoClose) {
                        isAutoClose = true;
                    } else {
                        isAutoClose = false;
                    }
                    return new MrcodePopLayer({
                        'position': "center",
                        'animateEntrance': 'flipInX',
                        'animateClosing': 'flipOutX',
                        'icon': "icon-spinner icon-2x icon-spin",
                        'content': body,
                        'autoClose': isAutoClose
                    });
                }
            },
            /**
             * 可关闭的提示框 2016.07.15
             * =================
             * 1. 依赖bootstrap
             */
            Dismissible:{
                /**
                 * js模版
                 * =================
                 * 1. 依赖arttemplate插件
                 * **/
                Tmpl:{
                    plane:function() {
                        return '<div class="alert {{className}} alert-dismissible text-center" role="alert">' +
                             '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                             '<span>{{msg}}</span>' +
                        '</div>';
                    }
                },
                /** 在网页内指定元素内显示一个提示框 */
                Plane:{
                    /**
                     *
                     * @param targetJqSelectName jquery 选择器名称
                     * @param msg  要提示的信息，可以是html
                     * @param className 提示框风格样式
                     */
                    base:function (targetJqSelectName,msg,className) {
                        var target = $(targetJqSelectName);
                        target.empty();
                        target.html(template.compile(MrcodeUi.Alert.Dismissible.Tmpl.plane())({
                            className:className,
                            msg:msg
                        }));
                    },
                    success:function (targetJqSelectName,msg) {
                        MrcodeUi.Alert.Dismissible.Plane.base(targetJqSelectName,msg,'alert-success');
                    },
                    err:function (targetJqSelectName,msg) {
                        MrcodeUi.Alert.Dismissible.Plane.base(targetJqSelectName,msg,'alert-danger');
                    },
                    info:function (targetJqSelectName,msg) {
                        MrcodeUi.Alert.Dismissible.Plane.base(targetJqSelectName,msg,'alert-info');
                    }
                }
            }
        },
        /** 按钮 */
        Btn: {
            /**
             * 新建一个控制按钮禁用激活的对象
             *  包含两个方法：
             *      1. disabled(msg) : 禁用按钮，msg = 禁用时显示的标题
             *      2. active(msg) : 激活按钮 msg = 激活时显示的标题
             *   示例：
             *      var newBtnDA = MrcodeUi.Btn.newBtnDA($submit,true);
             newBtnDA.disabled("处理中");
             newBtnDA.active("提交订单");
             * @param targetBtn jquery对象
             * @param isStandardBtn 是否是标准的input 按钮
             * @returns {BtnDa}
             */
            newBtnDA: function (targetBtn, isStandardBtn) {
                return new BtnDa(targetBtn, isStandardBtn);
            }
        }
    }


    /**
     * 可激活禁用按钮的功能对象
     * @param targetBtn 目标对象 jq对象
     * @param isStandardBtn 是否是原生btn
     * @param activeCssName 激活css
     * @param disabledCssName 禁用css
     * @constructor
     */
    var BtnDa = function (targetBtn, isStandardBtn, activeCssName, disabledCssName) {
        this.btn = targetBtn;
        this.isStandardBtn = isStandardBtn;
        this.activeCssName = activeCssName;
        this.disabledCssName = disabledCssName;
        this.activeMsg = "";
        this.disabledMsg = "";
    };

    /**
     * 可激活禁用按钮：禁用处理函数
     * @param targetBtn
     */
    function btnDa_disabledCss(me) {
        var targetBtn = me.btn;
        var activeCssName = me.activeCssName;
        var disabledCssName = me.disabledCssName;
        targetBtn.attr("disabled", true);
        if (disabledCssName) {
            targetBtn.addClass(disabledCssName);
            if (activeCssName) {
                targetBtn.removeClass(activeCssName);
            }
        }
    }

    /**
     * 可激活禁用按钮：激活处理函数
     * @param targetBtn
     */
    function btnDa_activeCss(me) {
        var targetBtn = me.btn;
        var activeCssName = me.activeCssName;
        var disabledCssName = me.disabledCssName;
        targetBtn.attr("disabled", false);
        if (activeCssName) {
            targetBtn.addClass(activeCssName);
            if (disabledCssName) {
                targetBtn.removeClass(disabledCssName);
            }
        }
    }

    BtnDa.prototype = {
        constructor: BtnDa,
        /**
         * 禁用按钮
         * @param msg 禁用按钮的标题
         */
        disabled: function (msg) {
            if (!msg) {
                msg = this.disabledMsg;
            }
            this.btn.val(msg);
            if (this.isStandardBtn) {
                btnDa_disabledCss(this);
            } else {
                this.btn.html('<span class="icon-spinner icon-spin"></span>' + msg);
                btnDa_disabledCss(this);
            }
        },
        /**
         * 激活按钮;
         * @param msg 激活标题：查找顺序：当前参数 --> activeMsg --> btn.attr("value")
         */
        active: function (msg) {
            if (!msg) {
                msg = this.activeMsg;
                if (!msg) {
                    msg = this.btn.attr("value");
                }
            }
            if (this.isStandardBtn) {
                this.btn.val(msg);
                btnDa_activeCss(this);
            } else {
                this.btn.html(msg);
                btnDa_activeCss(this);
            }
        },
        /**
         * 设置全局的 激活 禁用 内容
         * @param activeMsg
         * @param disabledMsg
         */
        setMsg: function (activeMsg, disabledMsg) {
            this.activeMsg = activeMsg;
            this.disabledMsg = disabledMsg;
        },
        /**
         * 设置全局的 disabledMsg 内容
         * @param disabledMsg
         */
        setDisabledMsg: function (disabledMsg) {
            this.disabledMsg = disabledMsg;
        }
    };
    window.MrcodeUi = MrcodeUi;
})(window);
